<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';
	const URLUPLOAD='/../images/profil/';
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('view','updateProfil', 'updatePassword', 'removeFoto', 'semua','captcha', 'lookup', 'bph', 'eksternal', 'internal', 'litbang'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete', 'create', 'resetPassword'),
				'expression'=>'$user->isSekretaris()',
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('register'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	public function actions()
	{
		return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
	}
	//PERHATIAN: KALAU MAU TAMBAH MENU SALAH SATU DIVISI, BISA TAMBAH ACTION DISINI DAN EDIT MENUNYA DI LAYOUT
	public function actionBph(){
		
		$bph = Riwayatdivisi::model()->findAll(array(
			'condition' => "divisi_id=3 and kepengurusan_id=".Tahunaktif::model()->findByPk(1)->kepengurusan_id,
			'order' => 'jabatan_id asc',
		));
		$this->render('bph',array(
			'modelBPH'=>$bph,
		));
	}
	public function actionEksternal(){
		$eks = Riwayatdivisi::model()->findAll(array(
			'condition' => "divisi_id=4 and kepengurusan_id=".Tahunaktif::model()->findByPk(1)->kepengurusan_id,
			'order' => 'jabatan_id asc',
		));
		$this->render('eksternal',array(
			'modelEks'=>$eks,
		));
	}
	public function actionLitbang(){
		$lit = Riwayatdivisi::model()->findAll(array(
			'condition' => "divisi_id=6 and kepengurusan_id=".Tahunaktif::model()->findByPk(1)->kepengurusan_id,
			'order' => 'jabatan_id asc',
		));
		$this->render('litbang',array(
			'modelLit'=>$lit,
		));
	}
	public function actionInternal(){
		$int = Riwayatdivisi::model()->findAll(array(
			'condition' => "divisi_id=5 and kepengurusan_id=".Tahunaktif::model()->findByPk(1)->kepengurusan_id,
			'order' => 'jabatan_id asc',
		));
		$this->render('internal',array(
			'modelInt'=>$int,
		));
	}
	
	public function actionRemoveFoto($id){
		$model = $this->loadModel($id);
		
		if(Yii::app()->user->id==$id || Yii::app()->user->isSekretaris()){
			if($model->foto!=null && $model->foto!="") {
				unlink(Yii::app()->basePath.self::URLUPLOAD.$model->foto.'');
				$fotoDihapus = $this->loadModelUserGantiFoto($id);
				$fotoDihapus->foto = null;
				$fotoDihapus->save(false);
			}
			Yii::app()->user->setFlash('success','Foto berhasil dihapus');
			$this->render('view',array(
				'model'=>$this->loadModel($id),
			));
		}else{
			throw new CHttpException(404,'The requested page does not exist.');
		}
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$modelUser = $this->loadModel($id);
		$model = $this->loadModelUserGantiFoto($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);		
		if(isset($_POST['UserGantiFoto']))
		{	
			$cekfoto=$model->foto=CUploadedFile::getInstance($model,'foto');
			if($model->validate()){
				if($modelUser->foto!=null && $modelUser->foto!="") unlink(Yii::app()->basePath.self::URLUPLOAD.$modelUser->foto.'');
				$model->attributes=$_POST['UserGantiFoto'];	
				//menyimpan url image ke database dengan nama username.jpg/png
				$model->setAttribute('foto',$modelUser->username . substr($model->foto, strlen($model->foto)-4, strlen($model->foto)));
			}
			if($model->save()){
				$cekfoto->saveAs(Yii::app()->basePath.self::URLUPLOAD.$modelUser->username.substr($model->foto, strlen($model->foto)-4, strlen($model->foto)).'');
				Yii::app()->user->setFlash('success','Foto berhasil diperbaharui');
			}else{
				Yii::app()->user->setFlash('error',$model->getError('foto'));
			}
		}
		
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			
			$cekfoto=$model->foto=CUploadedFile::getInstance($model,'foto');
			//save tanpa foto
			if(empty($cekfoto)){
				$model->attributes=$_POST['User'];
				
				if (isset($_POST['Nomorhp']))
				{
					$model->nomorhps = $_POST['Nomorhp'];
				}
				if (isset($_POST['Riwayatkelas']))
				{
					$model->riwayatkelases = $_POST['Riwayatkelas'];
				}
				if (isset($_POST['Riwayatdivisi']))
				{
					$model->riwayatdivisis = $_POST['Riwayatdivisi'];
				}
				if (isset($_POST['Mediasosial']))
				{
					$model->mediasosials = $_POST['Mediasosial'];
				}
				if ($model->saveWithRelated(array('nomorhps','riwayatkelases', 'riwayatdivisis', 'mediasosials'))){
					Yii::app()->user->setFlash('success','Anggota baru berhasil ditambahkan');
					$this->redirect(array('view', 'id' => $model->id));
				}
				
				
				
				
			//save dengan foto
			}else{
				$model->attributes=$_POST['User'];
				if (isset($_POST['Nomorhp']))
				{
					$model->nomorhps = $_POST['Nomorhp'];
				}
				if (isset($_POST['Riwayatkelas']))
				{
					$model->riwayatkelases = $_POST['Riwayatkelas'];
				}
				if (isset($_POST['Riwayatdivisi']))
				{
					$model->riwayatdivisis = $_POST['Riwayatdivisi'];
				}
				if (isset($_POST['Mediasosial']))
				{
					$model->mediasosials = $_POST['Mediasosial'];
				}
				if($model->validate())
					//menyimpan url image ke database dengan nama username.jpg/png
					$model->setAttribute('foto',$model->username . substr($model->foto, strlen($model->foto)-4, strlen($model->foto)));
				if($model->saveWithRelated(array('nomorhps','riwayatkelases', 'riwayatdivisis', 'mediasosials'))){
					//menyimpan foto ke direktori
					$cekfoto->saveAs(Yii::app()->basePath.self::URLUPLOAD.$model->username.substr($model->foto, strlen($model->foto)-4, strlen($model->foto)).'');
					Yii::app()->user->setFlash('success','Anggota baru berhasil ditambahkan');
					$this->redirect(array('view','id'=>$model->id));
					
				}
			}	
		}

		$this->render('create',array(
			'model'=>$model, 
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdateProfil($id)
	{
		$model=$this->loadModelUserUpdateProfil($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['UserUpdateProfil']))
		{
			$validasi_relasi = true;
			
			$model->attributes=$_POST['UserUpdateProfil'];
			if (isset($_POST['Nomorhp']))
            {
				$nomorhpp = array();
				foreach ($_POST['Nomorhp'] as $nohp) {
					$nohpModel = new Nomorhp;
					if(isset($nohp['id'])) $nohpModel = Nomorhp::model()->findByPk($nohp['id']);
					$nohpModel->user_id=$model->id;
					$nohpModel->nomorHp=$nohp['nomorHp'];
					if (!$nohpModel->validate()) $validasi_relasi = false; 
					$nomorhpp[] = $nohpModel;
				}
               $model->nomorhps = $nomorhpp;
            }
			if (isset($_POST['Riwayatkelas']))
			{
				$kelass = array();
				foreach ($_POST['Riwayatkelas'] as $kelas) {
					$kelasModel = new Riwayatkelas;
					if(isset($kelas['id'])) $kelasModel = Riwayatkelas::model()->findByPk($kelas['id']);
					$kelasModel->user_id = $model->id;
					$kelasModel->kelas_id = $kelas['kelas_id'];
					if (!$kelasModel->validate()) $validasi_relasi = false; //print_r($kelasModel->errors);
					$kelass[] = $kelasModel;
				}
				$model->riwayatkelases = $kelass;
			}
			if (isset($_POST['Riwayatdivisi']))
			{
				$divisis = array();
				foreach ($_POST['Riwayatdivisi'] as $divisi) {
					$divisiModel = new Riwayatdivisi;
					if(isset($divisi['id'])) $divisiModel= Riwayatdivisi::model()->findByPk($divisi['id']);
					$divisiModel->user_id = $model->id;
					$divisiModel->divisi_id = $divisi['divisi_id'];
					$divisiModel->jabatan_id = $divisi['jabatan_id'];
					$divisiModel->kepengurusan_id = $divisi['kepengurusan_id'];
					if (!$divisiModel->validate()) $validasi_relasi = false; //print_r($divisiModel->errors);
					$divisis[] = $divisiModel;
				}
				$model->riwayatdivisis = $divisis;
			}
			if (isset($_POST['Mediasosial']))
			{
				$medsoss = array();
				foreach ($_POST['Mediasosial'] as $medsos) {
					$medsosModel = new Mediasosial;
					if(isset($medsos['id'])) $medsosModel = Mediasosial::model()->findByPk($medsos['id']);
					$medsosModel->user_id = $model->id;
					$medsosModel->judul = $medsos['judul'];
					$medsosModel->isi = $medsos['isi'];
					if (!$medsosModel->validate()) $validasi_relasi = false; //print_r($divisiModel->errors);
					$medsoss[] = $medsosModel;
				}
				$model->mediasosials = $medsoss;
			}
			if ($validasi_relasi && $model->validate()){
				
				$trans = Yii::app()->db->beginTransaction();
				try{
					$model->save(false);
					//hapus data ketika ada salah satu data di form yang dihapus
					$dbh=Yii::app()->db;
					$sql="select id from nomorhp where user_id=".$model->id;
					$command=$dbh->createCommand($sql);
					$beforeNohp=$command->query();
					$hapusNohp = array();
					while(($value=$beforeNohp->read())!==false) $hapusNohp[] = $value['id'];
					
					$sql="select id from riwayatkelas where user_id=".$model->id;
					$command=$dbh->createCommand($sql);
					$beforeKelas=$command->query();
					$hapusKelas = array();
					while(($value=$beforeKelas->read())!==false) $hapusKelas[] = $value['id'];
					
					$sql="select id from riwayatdivisi where user_id=".$model->id;
					$command=$dbh->createCommand($sql);
					$beforeDivisi=$command->query();
					$hapusDivisi = array();
					while(($value=$beforeDivisi->read())!==false)  $hapusDivisi[] = $value['id'];
					
					$sql="select id from mediasosial where user_id=".$model->id;
					$command=$dbh->createCommand($sql);
					$beforeMedsos=$command->query();
					$hapusMedsos = array();
					while(($value=$beforeMedsos->read())!==false) $hapusMedsos[] = $value['id'];
					
					//update data ke database
					foreach ($model->nomorhps as $nohp) {
						if(in_array($nohp->id, $hapusNohp)) {
							if(($key = array_search($nohp->id, $hapusNohp)) !== false) {
								unset($hapusNohp[$key]);
							}
						}
						$nohp->save(false);
                    }
					foreach ($hapusNohp as $value) Nomorhp::model()->findByPk($value)->delete();
					
					foreach ($model->riwayatkelases as $kelas) {
						if(in_array($kelas->id, $hapusKelas)) {
							if(($key = array_search($kelas->id, $hapusKelas)) !== false) {
								unset($hapusKelas[$key]);
							}
						}
                        $kelas->save(false);
                    }
					foreach ($hapusKelas as $value) Riwayatkelas::model()->findByPk($value)->delete();
					
					foreach ($model->riwayatdivisis as $divisi) {
						if(in_array($divisi->id, $hapusDivisi)) {
							if(($key = array_search($divisi->id, $hapusDivisi)) !== false) {
								unset($hapusDivisi[$key]);
							}
						}
                        $divisi->save(false);
                    }
					foreach ($hapusDivisi as $value) Riwayatdivisi::model()->findByPk($value)->delete();
					
					foreach ($model->mediasosials as $medsos) {
						if(in_array($medsos->id, $hapusMedsos)) {
							if(($key = array_search($medsos->id, $hapusMedsos)) !== false) {
								unset($hapusMedsos[$key]);
							}
						}
                        $medsos->save(false);
                    }
					foreach ($hapusMedsos as $value) Mediasosial::model()->findByPk($value)->delete();
					
					$trans->commit();
					Yii::app()->user->setFlash('success','Profil berhasil diperbaharui');
					$this->redirect(array('view', 'id' => $model->id));
				}catch(Exception $e){
					 $trans->rollback();
					 Yii::app()->user->setFlash('error',$e->getMessage());
				}
				
			}
		}
		if(Yii::app()->user->id==$id || Yii::app()->user->isSekretaris()){
			$this->render('update',array(
				'model'=>$model,
			));
		}else{
			throw new CHttpException(404,'The requested page does not exist.');
		}
	}
	
	public function actionUpdatePassword()
	{
		$model=$this->loadModelUserUpdatePassword(Yii::app()->user->id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);		
		if(isset($_POST['UserUpdatePassword']))
		{	
			$validasi = true;
			$model->attributes=$_POST['UserUpdatePassword'];	
			if(!$model->validatePassword($model->oldPassword)){
				$model->addError('oldPassword','password lama salah! ');
				$validasi = false;
			}
			if($model->newPassword!==$model->rePassword){
				$model->addError('rePassword','password tidak sama! ');
				$validasi = false;
			}
			if($validasi){
				$model->password=$model->newPassword;
				$dua=$model->password;
				$model->saltPassword=$model->rePassword;
				$model->saltPassword=$model->generateSalt();
				$model->password=$model->hashPassword($dua,$model->saltPassword);
				if($model->save()){
					Yii::app()->user->setFlash('success','Password berhasil diperbaharui');
					$this->redirect(array('view', 'id' => $model->id));
				}
			}
			
		}
		$this->render('updatePassword',array(
			'model'=>$model,	
		));
	}
	public function actionResetPassword($id)
	{
		$model=$this->loadModelUserResetPassword($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);		
		if(isset($_POST['UserResetPassword']))
		{	
			$validasi = true;
			$model->attributes=$_POST['UserResetPassword'];	
			if($model->newPassword!==$model->rePassword){
				$model->addError('rePassword','password tidak sama! ');
				$validasi = false;
			}
			if($validasi){
				$model->password=$model->newPassword;
				$dua=$model->password;
				$model->saltPassword=$model->rePassword;
				$model->saltPassword=$model->generateSalt();
				$model->password=$model->hashPassword($dua,$model->saltPassword);
				if($model->save()){
					Yii::app()->user->setFlash('success','Password berhasil direset');
					$this->redirect(array('view', 'id' => $model->id));
				}
			}
			
		}
		if(!Yii::app()->user->isAdmin() && User::model()->findByPk($id)->levelUser_id==1){
			throw new CHttpException(404,'The requested page does not exist.');
		}
		
		$this->render('resetPassword',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$calonDihapus = $this->loadModel($id);
		if($calonDihapus->levelUser_id==1 && !Yii::app()->user->isAdmin()){
			if(!isset($_GET['ajax']))
				Yii::app()->user->setFlash('error','Hanya Admin yang dapat menghapus Admin');
			else
				echo "<div class='alert alert-error'>Hanya Admin yang dapat menghapus Admin</div>";
			return;
		}
		if($calonDihapus->foto!=null && $calonDihapus->foto!="") unlink(Yii::app()->basePath.self::URLUPLOAD.$calonDihapus->foto.'');
		
		$this->loadModel($id)->delete();
		if(!isset($_GET['ajax']))
			Yii::app()->user->setFlash('success','Berhasil Dihapus');
		else
			echo "<div class='alert alert-success'>Berhasil Dihapus</div>";
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionSemua()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	public function loadModelUserUpdateProfil($id)
	{
		$model=UserUpdateProfil::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	public function loadModelUserUpdatePassword($id)
	{
		$model=UserUpdatePassword::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	public function loadModelUserResetPassword($id)
	{
		$model=UserResetPassword::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	public function loadModelUserGantiFoto($id)
	{
		$model=UserGantiFoto::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionLookup() {
       $term = $_GET['term']; 
       // Buat objek user baru (Instantiasi) dan lakukan pencarian nama berdasar keyword yang dimasukkan
       $users = User::model()->findAll(array(
           'condition' => 'nama LIKE :parameter or username LIKE :parameter',
           'params' => array(
               ':parameter' => "%$term%",
           ),
       ));

       foreach ($users as $user){
           $return[] = array(
               'label' =>$user->nama,
               'value' =>$user->nama,
			   'link' =>$user->id,
               // konvensi
               'image' =>$user->ProfilePicturePath, // mengambil path dari gambar
               'nim'    =>$user->username,
           );
       }
       echo CJSON::encode($return);
    } 
}
